package com.sproutcat.sample;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

import java.util.Map;

/**
 * @author tzg
 */
@Configuration
@AutoConfigureAfter({ReceiverOne.class})
public class SubscriberConfig {

    /**
     * 注入消息监听适配器
     */
    @Bean
    public MessageListenerAdapter getMessageListenerAdapter(ReceiverOne receiver) {
        return new MessageListenerAdapter(receiver, "subscribeMessage");
    }

    /**
     * 注入消息监听适配器
     */
    @Bean
    public MessageListenerAdapter getMessageListenerAdapter2(ReceiverTwo receiver) {
        return new MessageListenerAdapter(receiver, "subscribeMessage");
    }

    /**
     * 注入消息监听容器
     */
    @Bean
    public RedisMessageListenerContainer getRedisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory, Map<String, MessageListenerAdapter> messageListenerAdapters) {
        RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();

        redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
        PatternTopic myChannel = new PatternTopic("myChannel");
        for (MessageListenerAdapter value : messageListenerAdapters.values()) {
            redisMessageListenerContainer.addMessageListener(value, myChannel);
        }

        return redisMessageListenerContainer;
    }

}
